package com.cybertron.ironhide.manage.common;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;

import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import com.octo.captcha.component.image.backgroundgenerator.BackgroundGenerator;

public class JCaptchaBackgroundGenerator implements BackgroundGenerator {
	private Integer width;
	private Integer height;
	private List<BufferedImage> images = new ArrayList<BufferedImage>();
	Random myRandom = new SecureRandom();

	public JCaptchaBackgroundGenerator(Integer width, Integer height,
			String matchPath) {
		this.width = width;
		this.height = height;
		PathMatchingResourcePatternResolver matchResource = new PathMatchingResourcePatternResolver();
		Resource[] resources = null;
		BufferedImage out = null;

		try {
			resources = matchResource.getResources(matchPath);
			for (Resource resource : resources) {
				InputStream is = resource.getInputStream();
				out = ImageIO.read(is);
				images.add(out);
				is.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	@Override
	public BufferedImage getBackground() {
		return this.images.get(this.myRandom.nextInt(this.images.size()));
	}

	@Override
	public int getImageHeight() {
		return height;
	}

	@Override
	public int getImageWidth() {
		return width;
	}

}
